const router = require('express').Router()
const U = require('../../utils')
const User = require('../../models/user')
const M = require('kobako-maybe')


function is_pass_correct(correct_user, user) {
  return correct_user.pass == user.pass
}

function abort_invalid_input(req, res, next) {
  const body = req.body
  if (body.user == null || body.pass == null) {
    res.json(U.Err('请提供用户名和密码'))
    return
  }
  next()
}

function wrap_correct_user(req, res, next) {
  const body = req.body
  const correct_user = User.get_by_user(body.user)
  if(correct_user == null){
    res.json(U.Err('没有这个用户'))
    return
  }
  req.correct_user = correct_user
  next()
}

function check_pass(req,res,next){
  if(req.correct_user.pass != req.body.pass){
    res.json(U.Err('密码不正确'))
    return
  }
  next()
}

router.post('/login', abort_invalid_input, wrap_correct_user, check_pass, (req, res, next) => {
  req.session.user = req.correct_user
  console.log(JSON.stringify(req.session.user))
  res.json(U.Ok('登陆成功'))
})

module.exports = router